package com.example.fitapp.activity.http.util;


import android.os.Handler;
import android.os.Looper;



import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class OkHttpCallback implements Callback {
    public abstract void onSuccess(final Call call, JSONObject jsonObject);
    protected Handler mOkHandler = null;
    @Override
    public void onResponse(final Call call,  Response response) throws IOException {
        if(response != null){
            try{
                if(isSuccess(response)){
                    onSuccess(call, response);
                }else{
                    String str = response.body().string().trim();
                    System.out.println(str);
                    onFailureRequest(call);
                }
            }catch (Throwable e){
                onFailureRequest(call);
            }
        } else{
            onFailureRequest(call);
//            String str = response.body().string().trim();
//            System.out.println(str);
    }
    }

    protected final void onSuccess(final Call call, Response response) throws Throwable {
        String responseStr = response.body().string().trim();
        JSONObject responseObject = (JSONObject)new JSONTokener(responseStr).nextValue();
        System.out.println(responseStr);
        if (responseObject != null) {
            onSuccessRequest(call, responseObject);
        } else {
            onFailureRequest(call);
        }
    }

    public void onSuccessRequest(final Call call, final JSONObject responseObject) {
        if(isPostMainThread()) {
            getOkHandler().post(new Runnable() {
                @Override
                public void run() {
                    onSuccess(call, responseObject);
                }
            });
        }else{
            onSuccess(call, responseObject);
        }
    }

    public void onFailureRequest(final Call call) {
        if(isPostMainThread()) {
            getOkHandler().post(new Runnable() {
                @Override
                public void run() {
                    onFailure(call, null);
                }
            });
        }else{
            onFailure(call, null);
        }
    }

    protected boolean isPostMainThread(){
        return true;
    }

    private boolean isSuccess(Response response){
        return response.isSuccessful()||response.code()==401;
    }


    public final Handler getOkHandler() {
        return mOkHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        e.printStackTrace();
    }
}
